package com.speechb.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.lucenex.base.Const;
import com.ld.lucenex.base.Page;
import com.ld.lucenex.core.LuceneX;
import com.ld.lucenex.query.QueryParser;
import com.ld.lucenex.service.ServiceFactory;
import com.speechb.common.html.HtmlUtil;
import com.speechb.common.text.TextUtil;
import com.speechb.entity.Blog;
import com.speechb.mapper.BlogMapper;
import com.speechb.service.IBlogService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 博客 服务实现类
 * </p>
 *
 * @author llj
 * @since 2021-03-14
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BlogServiceImpl.class);

    @Autowired
    BlogMapper blogMapper;

    @Override
    public List<Blog> findAll(Integer typeId) {
        return blogMapper.findAll(typeId);
    }

    @Override
    public Blog findContent(String id) {
        return blogMapper.findContent(id);
    }

    @Override
    public void updateScanCount(String id, int hot) {
        blogMapper.updateScanCount(id, hot);
    }

    @Override
    public Blog findById(String id) {
        return blogMapper.findById(id);
    }

    @Override
    public List<Blog> findLuceneData(String id) {
        List<Blog> blogList = blogMapper.findLuceneData(id);
        blogList.forEach(blog -> {
           blog.setHtml_content(HtmlUtil.cleanHtmlTag(blog.getHtml_content()));
        });
        return blogList;
    }


    @Override
    public List<Blog> findLuceneData() {
        List<Blog> blogList = findLuceneData(null);
        blogList.forEach(blog -> {
            blog.setHtml_content(HtmlUtil.cleanHtmlTag(blog.getHtml_content()));
        });
        return blogList;
    }

    @Override
    public Page<Blog> search(String keyword,int statusId, int pageNum, int pageSize, String uid) {
        com.ld.lucenex.service.ServiceImpl<Blog> basisService = ServiceFactory.getService(com.ld.lucenex.service.ServiceImpl.class);
        try {
            MultiFieldQueryParser multiFieldQueryParser = new MultiFieldQueryParser(new String[]{"html_content", "title"}, LuceneX.getIndexSource(Const.DEFAULT_SERVICE_KEY).getAnalyzer());
            Query query = multiFieldQueryParser.parse(keyword);
            QueryParser queryParser = new QueryParser();
            queryParser.addQuery(query, BooleanClause.Occur.MUST);

            BooleanQuery.Builder builder = new BooleanQuery.Builder();
            builder.add(IntPoint.newExactQuery("status",1), BooleanClause.Occur.SHOULD);
            if (StringUtils.isNotEmpty(uid)) {
                builder.add(new TermQuery(new Term("uid", uid)), BooleanClause.Occur.SHOULD);
            }
            BooleanQuery build = builder.build();
            queryParser.addQuery(build, BooleanClause.Occur.MUST);
            return basisService.searchList(queryParser.build() ,new Page<Blog>(pageNum, pageSize));
        } catch (IOException e) {
            LOGGER.error("Lucene failed to find Speechcraft", e);
        } catch (ParseException e) {
            LOGGER.error("Lucene failed to find Speechcraft", e);
        }
        return null;
    }

    @Override
    public void convertConverUrl(List<Blog> blogList) {
        if (CollectionUtils.isEmpty(blogList)) {
            return;
        }

        String tag;
        for (Blog blog : blogList) {
            // 从文章获取图片链接
            String content = blog.getHtml_content();
            blog.setImageUrl(TextUtil.getImgStr(content, 1));
            tag = blog.getTag();
            if (StringUtils.isNotEmpty(tag)) {
                blog.setTagList(tag.split("[,，]"));
            }
            blog.setHtml_content(null);
        }
    }

    @Override
    public List<Blog> findByUser(String uid, Integer status) {
        return blogMapper.findByUser(uid, status);
    }
}
